#include "s_oled_ssd1306_user.h"
#include "h_iic_s_user.h"

#include "s_oled_ssd1306.h"
#include "h_stm32_hal_timer.h"
#include "cmsis_os.h"

#include "h_ui.h"
#include "h_ui_basic_fonts.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

s_oled_ssd1306_t oled_t;
h_ui_t oled_ui_t;

static void iic_write(unsigned char reg, unsigned char *data, unsigned short len)
{
    h_iic_user_write_bytes(0x78, reg, data, len);
}

static void oled_draw_point(ui_position_type x, ui_position_type y, ui_color_type enable)
{
    s_oled_ssd1306_ext_draw_point(&oled_t, (unsigned char)x, (unsigned char)y, (unsigned char)enable);
}

static void oled_draw(void)
{
    s_oled_ssd1306_ext_buf_draw(&oled_t);
}

#define TIME_LEN                        (5 * 14 + 3 * 2 + 9)
#define TIME_START_X                    ((128 - TIME_LEN) / 2)
#define TIME_START_Y                    (25)

static unsigned int utc = 1608005743 + 8 * 3600;

void desk_monitor_oled_big_num(unsigned char x, unsigned char y, unsigned char num)
{
    if(num > ':' || num < '0') {
        return;
    }
    h_ui_draw_pic_with_single_color(&oled_ui_t, (ui_position_type)x, (ui_position_type)y, 14, 21, (unsigned char *)&big_num_14_21[(num - '0') * 37]);
}

void desk_monitor_oled_big_nums(unsigned char x, unsigned char y, unsigned char *num, unsigned char len)
{
    while(len--) {
        desk_monitor_oled_big_num(x, y, *num++);
        if(*(num-1) == ':') {
            x += 9;
        } else {
            x += 16;
        }
        
    }
}

void desk_monitor_oled_show_time(void)
{
    // s_normaltime_str nmt;
    unsigned char time_array[5];
    
    // S_UTC2NormalTime(utc++, &nmt);

    // time_array[0] = (nmt.hour / 10) + '0';
    // time_array[1] = (nmt.hour % 10) + '0';
    // time_array[2] = ':';
    // time_array[3] = (nmt.sec / 10) + '0';
    // time_array[4] = (nmt.sec % 10) + '0';

    time_array[0] = '0';
    time_array[1] = '0';
    time_array[2] = '0';
    time_array[3] = '0';
    time_array[4] = '0';


    desk_monitor_oled_big_nums(TIME_START_X, TIME_START_Y, time_array, sizeof(time_array));

    printf("%s\n", time_array);

}


void s_oled_ssd1306_user_init(void)
{
	h_iic_s_user_init();

	// h_iic_user_test();

	oled_t.ssd1306_write = &iic_write;
    oled_t.delay_ms = &delay_ms;

    s_oled_ssd1306_para_init(&oled_t);
    s_oled_ssd1306_init(&oled_t);

    oled_t.oled_malloc = &malloc;
    printf("s_oled_ssd1306_ext_init:%d\r\n", s_oled_ssd1306_ext_init(&oled_t));

    h_ui_init(&oled_ui_t, &oled_draw_point, &oled_draw, NULL, oled_t.colunm, oled_t.row);

    s_oled_ssd1306_ext_uptodown_change(&oled_t);

    h_ui_clear(&oled_ui_t, 0x00);

    // oled_ui_t.ui_draw();

    s_oled_ssd1306_set_brightness(&oled_t, 255);

    // desk_monitor_oled_show_time();
    // h_ui_moveTo(&oled_t, 0, 0);
    // h_ui_draw_string_len_with_single_color(&oled_ui_t, 0, 0, "1234", 4);
    oled_ui_t.ui_draw();
}

